home *** CD-ROM | disk | FTP | other *** search
Text File | 1989-10-20 | 2.9 KB | 84 lines | [TEXT/GEOL] |
- Item 3102473 19-Oct-89 09:38
-
- From: SCHMUCKER1 Schmucker, Kurt
-
- To: D0220 American Zettler, Dirk Tjossen,PRT
-
- cc: MACAPP.TECH$ MACAPP Tech
- DEREK White, Derek
-
- Sub: Re: Object Casting…
-
- Dirk,
-
- The object casting issue you bring up has to do with the REFERENCE Type of
- an object (what the compiler thinks it is) and the ACTUAL type (what it really
- is). These are sometimes the same, but not always. One case where they are
- usually different is in Lists.
-
- Suppose that we have the following classes:
-
- TMammal = OBJECT (TObject)
- Procedure TMammal.Eat;
- End;
-
- TCat = OBJECT (TMammal)
- Procedure TCat.Eat; OVERRIDE;
- Procedure TCat.Meow;
- End;
-
- TDog = OBJECT (TMammal)
- Procedure TDog.Eat; OVERRIDE;
- Procedure TDog.Bark;
- End;
-
- and further suppose that aDog, aCat, and a Mammal are three instances.
-
- Then the compiler will do the right thing if we say
-
- aDog.Eat (TDog.Eat will be called)
- aCat.Eat (TCat.Eat will be called)
- aDog.Bark (OK)
- aCat.Meow (OK)
-
-
- However, if we do this, there will be SOME problems:
-
- aMammal := aDog; (anObject is now REALLY a TDog. That is, its
- actual type is TDog. Its reference type is still
- TMammal. The reference type of an object is
- fixed at compile time. The actual type may vary
- during the execution of the program.)
-
- aMammal.Eat; (No problem. TDog.Eat will be called. The actual
- type, i.e., the run-time type, is used for message
- dispatching.)
-
- aMammal.Bark; (Problem. Since the reference type is TMammal and
- since mammals don't have a Bark method, the
- compiler won't compile this for you, EVEN THOUGH
- would be OK at run-time. The compiler doesn't
- know this and thus would not let you put yourself
- into a situation where there COULD be a run-time
- error.)
-
- TDog(aMammal).Bark; (OK)
-
-
- In Object Pascal, lists are usually type homogeneous, and usually the
- reference type of the elements in the list is TObject, even if the actual type
- is TView or something. Thus, when you pull something out of a list, the
- compiler won't let you send it any message not defined for TObject, without the
- additional assurance from you of what the actual type really is. This
- assurance takes the form of a type cast, like this:
-
-
- TDog(myAnimalList.FirstThat(FooBar)).Bark; (OK)
-
-
-
- Hope this helps you over one of Object Pascal's trickier parts,
-
- Kurt
-
-